package org.example.library.controller;

import com.alibaba.fastjson.JSONObject;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.library.HelloServlet;
import org.example.library.dao.UserDao;
import org.example.library.service.UserService;
import org.example.library.util.JsonUtils;
import org.example.library.util.ResponseUtil;
import org.example.library.vertile.User;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
@WebServlet("/user/*")
public class UserController extends HttpServlet {
    UserService userService = new UserService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        resp.setCharacterEncoding("utf-8");
        String uri = req.getRequestURI();
        switch (uri){
            case "/user/register"->doRegister(req,resp);
            case "/user/login"->doLogin(req,resp);
            default->{

            }
        }
    }

    private void doLogin(HttpServletRequest req, HttpServletResponse resp) throws  IOException{
        JSONObject json = JsonUtils.getJson(req);
        String username = json.getString("username");
        String password = json.getString("password");
        int res = new UserService().login(username,password);
        req.getSession().setAttribute("user",username);
        switch (res){
            case 0 -> ResponseUtil.gen500Response(resp,"用户名或密码不能为空");
            case -1 -> ResponseUtil .gen404Response(resp,"登录失败");
            case 1 -> ResponseUtil .genSuccessResponse(resp,"登录成功","null");
        }
    }

    private void doRegister(HttpServletRequest req, HttpServletResponse resp) throws  IOException{
        JSONObject json = JsonUtils.getJson(req);
        String username = json.getString("username");
        String password = json.getString("password");
        int res = new UserService().register(username,password);
        switch (res){
            case -1-> ResponseUtil.gen404Response(resp,"用户已存在");
            case 0 -> ResponseUtil.gen500Response(resp,"用户名或密码不能为空");
            case 1 -> ResponseUtil.genSuccessResponse(resp,"注册成功","null");
        }
    }

}
